package com.bookstore;

import com.bookstore.bean.Usuario;
import com.bookstore.db.BookStoreDao;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BuyActivity extends MenuActivity {
	private static final int ACTIVITY_COMPRAS = 6;
	private static final int ACTIVITY_REGISTER = 7;
	private static final int ACTIVITY_VIEW_CART = 8;
	private BookStoreDao dao;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.buy_login);

		if (BookStoreActivity.usuario != null) {
			Intent i = new Intent(BuyActivity.this, ViewCartActivity.class);
			startActivityForResult(i, ACTIVITY_VIEW_CART);
		} else {
			
			if (dao == null) {
				dao = new BookStoreDao(this);
				dao.open();
			}

			Button register = (Button) findViewById(R.id.register);
			Button buy = (Button) findViewById(R.id.enter);

			register.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					Intent i = new Intent(BuyActivity.this,
							RegisterActivity.class);
					startActivityForResult(i, ACTIVITY_REGISTER);
				}
			});

			buy.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {

					EditText usuario = (EditText) findViewById(R.id.user);
					EditText clave = (EditText) findViewById(R.id.pass);

					Usuario bean = dao.fetchUsuario(usuario.getText()
							.toString().trim());

					TextView msj = (TextView) findViewById(R.id.lo_msj);
					if (usuario.getText().toString().trim().length() == 0) {
						msj.setText("El Usuario es Requerido");
					} else if (clave.getText().toString().trim().length() == 0) {
						msj.setText("La Clave es Requerida");
					} else if (bean == null) {
						msj.setText("El Usuario no existe");
					} else if (!bean.getClave().equalsIgnoreCase(
							clave.getText().toString().trim())) {
						msj.setText("La Clave no coincide");
					} else {
						BookStoreActivity.usuario = bean;
						
						if (BookStoreActivity.viewCart){
							Intent i = new Intent(BuyActivity.this,
									ViewListCartActivity.class);
							startActivityForResult(i, ACTIVITY_COMPRAS);
						}else{
							Intent i = new Intent(BuyActivity.this,
									ViewCartActivity.class);
							startActivityForResult(i, ACTIVITY_VIEW_CART);
						}						
					}
				}
			});
		}
	}
}
